package net.xdclasss.demo_project.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.xdclasss.demo_project.domain.User;
import net.xdclasss.demo_project.service.impl.UserServiceImpl;
import net.xdclasss.demo_project.utils.JsonData;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginIntercepter implements HandlerInterceptor {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)){
            // 判断token是否合法
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null){
                return true;
            } else {
                rederJson(resp, JsonData.bulidError(-3,"登录失败，token失效"));
                return false;

            }
        }else {
            rederJson(resp,JsonData.bulidError(-4,"未登录"));
            return false;
        }

    }
    public JsonData rederJson(HttpServletResponse resp, JsonData jsonData){
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");

        try(PrintWriter writer = resp.getWriter()) {
            String strJson = objectMapper.writeValueAsString(jsonData);
            writer.print(strJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonData;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle====");
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}
